package com.lebang.controller.api.donwn.newapi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lebang.aop.Sessionid;
import com.lebang.common.MemberLock;
import com.lebang.common.Require;
import com.lebang.common.ValidCode;
import com.lebang.component.RedisClient;
import com.lebang.configuration.datasource.DataSource;
import com.lebang.domain.*;
import com.lebang.entity.RequestHeaders;
import com.lebang.model.Whether;
import com.lebang.model.enums.buss.DownStatus;
import com.lebang.service.*;
import com.lebang.service.earn.DownMemberCountConfigService;
import com.lebang.service.sys.DictService;
import com.lebang.service.sys.DownFailConfigService;
import com.lebang.service.sys.LookWhiteRecordService;
import com.lebang.service.sys.PkgEarnInfoService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static com.lebang.service.sys.AdErrorConfigService.LOCK_KEY;

/**
 * @Author: hwq
 * @Date: 2019/12/23 17:01
 * @Version 1.0
 */
@Api(tags = "下载任务")
@RestController
public class newApi {
    @Autowired
    private AppEarnRouseSortService appEarnRouseSortService;
    @Autowired
    private DownAppService downAppService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private CpaService cpaService;
    @Autowired
    private NewRouseService newRouseService;
    @Autowired
    private MemberNewTaskService memberNewTaskService;

    @Autowired
    private DownMemberCountConfigService downMemberCountConfigService;
    @Autowired
    private DownFailConfigService downFailConfigService;
    @Autowired
    private DictService dictService;

    @Autowired
    private PkgEarnInfoService pkgEarnInfoService;
    @Autowired
    private LookWhiteRecordService lookWhiteRecordService;


    /**
     * 1
     *
     * @param request
     * @return
     */
    @Require
    //@Sessionid
    @PostMapping("/appv2/download/pull")
    @MemberLock
    public JsonData record(HttpServletRequest request) {
        int weight = 1;
        RequestHeaders header = new RequestHeaders(request);

        int version = Integer.parseInt(header.getVersion());
        if (version <= 0) {
            return Callback.fail("200", "版本错误！");
        }


        int wall = downMemberCountConfigService.checkCountByMemberId(header.getUserid());
        //检测放弃频繁
        if (dictService.selectIntByKeyName("open_fail_check") == 1) {
            Long time = downFailConfigService.checkFail(header);
            if (time > 0) {
                return Callback.fail("207", "任务放弃过于频繁,请" + time + "秒后再来~", time);
            }
        }
        //检测次数是否用完
        if (downAppService.checkPushV2(header, wall, header.getAppStore())) {
            return zyCheck(header);
        }
        //检测是否超过了每小时限制
        if (redisClient.exists(downAppService.getExpreKey(header.getUserid()))) {
            return Callback.fail("208", "超过每小时上限", redisClient.ttl(downAppService.getExpreKey(header.getUserid())));
        }
        //获取用户当前第几次
        int count = downAppService.getTodayCountV2(header.getUserid());
        JSONObject jsonObject = new JSONObject();
        String skdKey = "";
        int type = 0;
        TaskRouse rouse;
        AppEarnRouseSort appEarnRouseSort = appEarnRouseSortService.getByCount(count, header.getAppStore());
        if (appEarnRouseSort == null) {
            return Callback.fail("200", "次数已用完!");
        }
        if (appEarnRouseSortService.check(appEarnRouseSort, version)) {
            if ("random".equals(appEarnRouseSort.getSdkKey())) {
                rouse = downAppService.getRandomAllKey(header.getAppStore(), version, header.getUserid());
                if (rouse == null) {
                    return Callback.fail("200", "{2001} 次数已用完!");
                }
                skdKey = rouse.getSdkKey();
                type = appEarnRouseSort.getType() == 2 ? downAppService.randomPullV2() : appEarnRouseSort.getType();
            } else {
                skdKey = appEarnRouseSort.getSdkKey();
                type = appEarnRouseSort.getType() == 2 ? downAppService.randomPullV2() : appEarnRouseSort.getType();
                rouse = downAppService.selectByKey(skdKey);
            }
        } else {
            rouse = downAppService.getRandomAllKey(header.getAppStore(), version, header.getUserid());
            if (rouse == null) {
                return Callback.fail("200", "{2002} 次数已用完!");
            }
            skdKey = rouse.getSdkKey();
            type = downAppService.randomPullV2();
        }
        TaskRouseDetail detail = null;
        DownloadMemberRecord record;
        if (cpaService.getZyData().equals(skdKey)) {
            detail = cpaService.getDetailByZy(header.getUserid(), header);
            if (detail == null) {
                //没自营数据源的时候取一个非自营数据源
                rouse = downAppService.getRandomAllKeyNotZy(header.getAppStore(), version, header.getUserid());
                if (rouse == null) {
                    return Callback.fail("209", "任务被抢光啦");
                }
                skdKey = rouse.getSdkKey();
            } else {
                jsonObject.put("detail", detail);
            }
        }
        if (rouse == null) {
            return Callback.fail("209", "任务被抢光啦");
        }
        //自营数据源
        if (cpaService.getZyData().equals(skdKey)) {
            record = cpaService.pull(header.getUserid(), header, detail);
        } else {
            List<String> strings = getSortList(header);
            if (redisClient.exists(LOCK_KEY + header.getUserid() + rouse.getSdkKey())) {
                return Callback.fail("209", "当前抢夺人数过多,请"
                        + redisClient.ttl(LOCK_KEY + header.getUserid() + rouse.getSdkKey()) / 60 + "分钟后再来");
            }
            rouse = downAppService.checkSdkMax(rouse, header, strings);
            if (rouse == null) {
                return Callback.fail("209", "今日暂无任务，请明日再来");
            }
            record = downAppService.pull(header.getUserid(), type, header, rouse);
        }
        jsonObject.put("open_return", rouse.getOpenReturn());
        jsonObject.put("type", type);
        jsonObject.put("recordId", record.getId());
        jsonObject.put("time", record.getTime());
        jsonObject.put("sdk_key", record.getSdkKey());
        jsonObject.put("count", downAppService.getCountV2(header.getUserid(), header.getAppStore()));
        return Callback.success("success", "查询成功", jsonObject);
    }


    /**
     * 2
     *
     * @param request
     * @param appName
     * @param pkgName
     * @param recordId
     * @param sdkKey
     * @return
     */
    @Require
    @PostMapping("/app/download/init/record")
    @ApiOperation("填充任务参数")
    public JsonData newcheckAppName(HttpServletRequest request,
                                    @ApiParam(name = "应用名称") String appName,
                                    @ApiParam(name = "包名") String pkgName,
                                    Integer recordId,
                                    String sdkKey, Integer type, Integer downType) {
        if (recordId == null) {
            return Callback.fail("200", "任务id为空");
        }
        JSONObject jsonObject = new JSONObject();
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String memberId = requestHeaders.getUserid();
        DownloadMemberRecord record = downAppService.selectByRecordId(recordId);
        if (record == null) {
            return Callback.fail("200", "任务不存在");
        }
        if (cpaService.getZyData().equals(record.getSdkKey())) {
            return Callback.fail("200", "任务错误");
        }
        if (!record.getMemberId().equals(memberId)) {
            return Callback.fail("200", "任务不存在");
        }
        if (!record.getStatus().equals(DownStatus.WAIT_PUSH.getIndex())) {
            return Callback.fail("200", "任务不存在");
        }
        if (!TextUtil.isEmpty(type)) {
            record.setType(type);
        }
        if (!TextUtil.isEmpty(downType)) {
            record.setDownType(downType);
        }
        record = downAppService.initRecord(appName, memberId, record, pkgName);
        jsonObject.put("worth", record.getMoney());
        jsonObject.put("type", record.getRewardType());
        int version = Integer.parseInt(requestHeaders.getVersion());
        if (version >= 126) {
            jsonObject.put("count", downAppService.getCountV2(memberId, requestHeaders.getAppStore()) - 1);
        } else {
            jsonObject.put("count", downAppService.getCount(memberId) - 1);
        }
        return Callback.success("success", "查询成功", jsonObject);
    }

    /**
     * 3
     *
     * @param request
     * @param appName
     * @param pkgName
     * @return
     */
    @Require
    @PostMapping("/app/download/check")
    @ApiOperation("验证今天做没做过这个任务")
    public JsonData check(HttpServletRequest request, String appName, String pkgName) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String memberId = requestHeaders.getUserid();
        if ("com.zqcm.ysp".equals(pkgName)) {
            return Callback.success("success", "查询成功", true);
        }
        if (TextUtil.isEmpty(pkgName)) {
            return Callback.success("success", "查询成功", false);
        }
        if (!pkgEarnInfoService.checkPkgName(pkgName, appName)) {
            return Callback.success("success", "查询成功", true);
        }
        return Callback.success("success", "查询成功", downAppService.selectByAppNameAndMemberIdToday(appName, memberId, pkgName) != null);
    }


    /**
     * 第四步
     *
     * @param request
     * @param recordId
     * @return
     */
    @Require
    @PostMapping("/app/download/downEnd")
    @ApiOperation("下载完成调用")
    public JsonData downEnd(HttpServletRequest request, @ApiParam(name = "任务id") Integer recordId) {
        if (recordId == null) {
            return Callback.fail("200", "参数非法");
        }
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String memberId = requestHeaders.getUserid();
        DownloadMemberRecord record = downAppService.selectByRecordId(recordId);
        if (record == null) {
            return Callback.fail("200", "任务不存在");
        }
        if (!record.getMemberId().equals(memberId)) {
            return Callback.fail("200", "任务不存在");
        }
        if (!record.getStatus().equals(DownStatus.WAIT_PUSH.getIndex())) {
            return Callback.fail("200", "任务不存在");
        }
        return Callback.success("success", "领取成功", downAppService.downEnd(record));
    }

    /**
     * 第5步
     *
     * @param request
     * @param recordId
     * @param icon
     * @param category
     * @return
     */
    @Sessionid
    @Require
    @PostMapping("/appv2/download/push")
    @ApiOperation("提交任务")
    @ValidCode
    @MemberLock
    public JsonData push(HttpServletRequest request,
                         @ApiParam(name = "任务id") Long recordId,
                         @ApiParam(name = "图标") String icon,
                         Integer category,String adId) {
        if (category == null) {
            return Callback.fail("201", "参数非法");
        }
        if (recordId == null) {
            return Callback.fail("201", "参数非法");
        }
        RequestHeaders header = new RequestHeaders(request);
        String memberId = header.getUserid();
        DownloadMemberRecord record = downAppService.selectByRecordId(recordId);
        if (record == null) {
            return Callback.fail("201", "任务不存在");
        }
        boolean isZy = record.getSdkKey().equals(cpaService.getZyData());
        //检测是否超过了每小时限制
        if (redisClient.exists(downAppService.getExpreKey(memberId)) && !isZy) {
            return Callback.fail("208", "超过每小时上限", redisClient.ttl(downAppService.getExpreKey(memberId)));
        }

        int wall = downMemberCountConfigService.checkCountByMemberId(header.getUserid());
        if (downAppService.checkPushV2(header, wall, header.getAppStore()) && !isZy) {
            return Callback.fail("207", "今日暂无任务，请明日再来");
        }
        if (!record.getMemberId().equals(memberId)) {
            return Callback.fail("202", "任务不存在.");
        }
        if (record.getEndTime() == null) {
            return Callback.fail("203", "任务不存在..");
        }
        if (!record.getStatus().equals(DownStatus.WAIT_PUSH.getIndex())) {
            return Callback.fail("204", "任务不存在...");
        }
        boolean i = LocalDateTime.now().plusSeconds(record.getTime()).isAfter(record.getEndTime());
        if (!i) {
            return Callback.fail("205", "任务失败还没到体验时间呢");
        }
        downAppService.addDownCount(record);
        if (!TextUtil.isEmpty(record.getRouseDetailId())) {
            cpaService.pushByDetail(record, header, category);
        } else {
            downAppService.push(recordId, category, header, icon,adId);
        }
        //今日个人次数+1
        downAppService.addV2(header, record.getSdkKey());
        int success = downAppService.getSuccessByMemberId(record.getMemberId());
        //每日必赚新手任务完成
        memberNewTaskService.addMrbz(success, record.getMemberId());
        //清除签到列表缓存
        redisClient.hdel(downAppService.getClickCacheKey(), memberId);
        //今日总次数+1
        downAppService.addSuccessCount();
        downAppService.checkHasRecord(header);
        return Callback.success("success", "领取成功，奖励已发放");
    }

    public JsonData zyCheck(RequestHeaders header) {
        JSONObject jsonObject = new JSONObject();
        TaskRouseDetail detail = cpaService.getDetailByZy(header.getUserid(), header);
        if (detail == null) {
            return Callback.fail("207", "今日暂无任务，请明日再来");
        }
        DownloadMemberRecord record = cpaService.pull(header.getUserid(), header, detail);
        jsonObject.put("open_return", 1);
        jsonObject.put("type", 1);
        jsonObject.put("recordId", record.getId());
        jsonObject.put("time", record.getTime());
        jsonObject.put("sdk_key", record.getSdkKey());
        jsonObject.put("count", downAppService.getCountV2(header.getUserid(), header.getAppStore()));
        jsonObject.put("detail", detail);
        return Callback.success("success", "查询成功", jsonObject);
    }

    public List<String> getSortList(RequestHeaders headers) {
        List<String> strings = new ArrayList<>();
        Optional<String> sortList = Optional.ofNullable(redisClient.hget("down_sortlist", headers.getAppStore()));
        if (sortList.isPresent()) {
            strings = JSON.parseArray(sortList.get(), String.class);
        } else {
            List<TaskRouse> rouses = newRouseService.selectAllByEnable(headers);
            for (TaskRouse next : rouses) {
                if (!cpaService.getZyData().equals(next.getSdkKey())) {
                    strings.add(next.getSdkKey());
                }
            }
            redisClient.hset("down_sortlist", headers.getAppStore(), JSON.toJSONString(strings));
        }
        List<String> filterSdkKey = downAppService.filterSdkKey(headers.getUserid());
        strings.removeAll(filterSdkKey);
        return strings;
    }
    @DataSource("commonDB")
    @PostMapping("/appv2/download/whtie")
    public JsonData white(HttpServletRequest request, String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        JSONObject appManage = jsonObject.getJSONObject("app_manage");
        if (appManage != null) {
            String appName = appManage.getString("app_name");
            String packageName = appManage.getString("package_name");
            if (packageName != null) {
                LookWhiteRecord lookWhiteRecord = new LookWhiteRecord();
                lookWhiteRecord.setCreateTime(LocalDateTime.now());
                lookWhiteRecord.setModifyTime(LocalDateTime.now());
                lookWhiteRecord.setPkgName(packageName);
                lookWhiteRecord.setJson(json);
                lookWhiteRecord.setAppName(appName);
                lookWhiteRecord.setHasDeleted(0);
                LookWhiteRecord b = lookWhiteRecordService.checkPkg(packageName);
                if (b == null) {
                    lookWhiteRecord.setEnable(Whether.YES.getDbIndex());
                    lookWhiteRecordService.insertModel(lookWhiteRecord);
                    return Callback.success("success", "查询成功");
                } else {
                    lookWhiteRecord.setId(b.getId());
                    lookWhiteRecordService.updateById(lookWhiteRecord);
                    if(b.getEnable().equals(Whether.YES.getDbIndex())){
                        return Callback.success("success", "查询成功");
                    }else {
                        return Callback.fail("success", "查询成功");
                    }
                }
            }
        }
        return Callback.fail("success", "查询成功");
    }

    public static void main(String[] args) {
        List<String> a = new ArrayList<>();
        a.add("1");
        a.add("2");
        a.add("3");
        a.add("4");
        List<String> b = new ArrayList<>();

        a.removeAll(b);
        System.out.println(a);

    }
}
